#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API网关自动注册器
HAI优化系统启动时自动注册到API网关
"""

import time
import logging
import threading
import requests
from typing import Optional
try:
    from ..config.config import CONFIG
except ImportError:
    from config.config import CONFIG

logger = logging.getLogger(__name__)

class APIGatewayRegistry:
    """API网关自动注册器"""
    
    def __init__(self, gateway_url: str = None, 
                 server_ip: str = "127.0.0.1", server_port: int = None,
                 secret: str = None):
        """
        初始化API网关注册器
        
        Args:
            gateway_url: API网关URL（如果为None则从配置读取）
            server_ip: HAI优化系统IP
            server_port: HAI优化系统端口（如果为None则从配置读取）
            secret: 注册密钥（如果为None则从配置读取）
        """
        # 从配置读取默认值
        config = CONFIG.get('api_gateway_registration', {})
        
        self.gateway_url = gateway_url or config.get('gateway_url', 'https://gongjuxiang.work')
        self.server_ip = server_ip
        self.server_port = server_port or config.get('server_port', 8080)
        self.secret = secret or config.get('secret', 'gpu-server-register-to-api-gateway-2024')
        self.registered = False
        self.registration_thread = None
        self.running = False
        self.enabled = config.get('enabled', True)
        
        logger.info(f"API网关注册器已初始化: {self.gateway_url} (启用状态: {self.enabled})")
    
    def register_to_gateway(self) -> bool:
        """
        注册到API网关
        
        Returns:
            是否注册成功
        """
        try:
            # 准备注册数据
            registration_data = {
                "ip": self.server_ip,
                "port": self.server_port,
                "secret": self.secret
            }
            
            # 发送注册请求
            response = requests.post(
                f"{self.gateway_url}/webhook/register",
                json=registration_data,
                timeout=10
            )
            
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    self.registered = True
                    server_id = result.get('server_id', 'HAI-OPT-001')
                    logger.info(f"HAI优化系统已成功注册到API网关: {server_id}")
                    return True
                else:
                    logger.error(f"注册失败: {result.get('error')}")
                    return False
            else:
                logger.error(f"注册请求失败: HTTP {response.status_code}")
                return False
                
        except requests.exceptions.ConnectionError:
            logger.warning("无法连接到API网关，稍后重试")
            return False
        except requests.exceptions.Timeout:
            logger.warning("注册请求超时，稍后重试")
            return False
        except Exception as e:
            logger.error(f"注册过程中出错: {e}")
            return False
    
    def start_auto_registration(self, max_attempts: int = None, interval: int = None):
        """
        启动自动注册
        
        Args:
            max_attempts: 最大尝试次数（如果为None则从配置读取）
            interval: 重试间隔（秒）（如果为None则从配置读取）
        """
        # 检查是否启用自动注册
        if not self.enabled:
            logger.info("API网关自动注册已禁用，跳过启动")
            return
        
        if self.registration_thread and self.registration_thread.is_alive():
            logger.warning("自动注册已在运行")
            return
        
        # 从配置读取默认值
        config = CONFIG.get('api_gateway_registration', {})
        max_attempts = max_attempts or config.get('max_attempts', 10)
        interval = interval or config.get('retry_interval', 30)
        
        self.running = True
        self.registration_thread = threading.Thread(
            target=self._auto_registration_loop,
            args=(max_attempts, interval),
            daemon=True
        )
        self.registration_thread.start()
        logger.info(f"API网关自动注册已启动 (最大尝试: {max_attempts}, 间隔: {interval}秒)")
    
    def _auto_registration_loop(self, max_attempts: int, interval: int):
        """自动注册循环"""
        attempts = 0
        
        while self.running and attempts < max_attempts:
            if self.registered:
                # 已经注册成功，定期检查状态
                time.sleep(interval)
                continue
            
            attempts += 1
            logger.info(f"尝试注册到API网关 (第 {attempts}/{max_attempts} 次)")
            
            if self.register_to_gateway():
                logger.info("自动注册成功")
                break
            
            if attempts < max_attempts:
                logger.info(f"注册失败，{interval}秒后重试...")
                time.sleep(interval)
        
        if not self.registered:
            logger.error(f"自动注册失败，已尝试 {max_attempts} 次")
    
    def stop_auto_registration(self):
        """停止自动注册"""
        self.running = False
        if self.registration_thread:
            self.registration_thread.join(timeout=5)
        logger.info("自动注册已停止")
    
    def is_registered(self) -> bool:
        """检查是否已注册"""
        return self.registered
    
    def get_registration_status(self) -> dict:
        """获取注册状态"""
        return {
            "registered": self.registered,
            "gateway_url": self.gateway_url,
            "server_url": f"http://{self.server_ip}:{self.server_port}",
            "running": self.running
        }

# 全局实例
api_gateway_registry = APIGatewayRegistry()
